package com.sk.waste.app.fragments

import android.Manifest
import android.app.Activity.RESULT_OK
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.Button
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCBaseUtil
import com.lc.smc.lib.utils.LCBaseUtil.showToast
import com.lc.smc.lib.utils.LCLogger
import com.lc.smc.lib.utils.LCSPUtil
import com.sk.pay.lib.PaymentUtil
import com.sk.waste.app.R
import com.sk.waste.app.activitys.CollectionActivity
import com.sk.waste.app.activitys.LoginActivity
import com.sk.waste.app.activitys.MainActivity
import com.sk.waste.app.activitys.MyPushActivity
import com.sk.waste.app.activitys.RegisterActivity
import com.sk.waste.app.activitys.ResetPassActivity
import com.sk.waste.app.activitys.VipBuyActivity
import com.sk.waste.app.activitys.WebViewActivity
import com.sk.waste.app.application.MyApplication
import com.sk.waste.app.bases.BaseFragment
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.enums.IdenEmum
import com.sk.waste.app.models.MaterialModel
import com.sk.waste.app.models.UserModel
import com.sk.waste.app.utils.BaseUtil
import com.sk.waste.app.utils.OkHttpUtil
import com.sk.waste.app.utils.PermissionUtil
import com.sk.waste.app.utils.UpdateUtil
import com.sk.waste.app.views.SkAlertDialog
import com.sking.album.utils.SKRPhotoSelectUtil
import com.sking.album.view.AlbumSelectPopuWindow
import okhttp3.Call
import org.json.JSONObject
import java.io.IOException


/**
 * 个人中心
 */
class MineFragment : BaseFragment() {

    private lateinit var imgAvatar: ImageView
    private lateinit var ttvName: TextView
    private lateinit var ttvPhone: TextView
    private lateinit var ttvAdress: TextView
    private lateinit var ttvVipState: ImageView
    private lateinit var ttvEditInfo: TextView
    private lateinit var ttvVipBuy: FrameLayout
    private lateinit var bttVipBuy: Button
    private lateinit var ttvRestPass: TextView
    private lateinit var ttvCollection: TextView
    private lateinit var ttvMyPush: TextView
    private lateinit var ttvClearCache: TextView
    private lateinit var ttvCheckUpdate: TextView
    private lateinit var ttvPrivacy: TextView
    private lateinit var ttvLogOff: TextView
    private lateinit var bttExitLogin: Button

    private var userInfo: UserModel? = null
    private var cacheDialog: SkAlertDialog? = null

    private lateinit var photoSelectUtil: SKRPhotoSelectUtil
    private lateinit var albumSelectPopuWindow: AlbumSelectPopuWindow
//    private var currentAvatarPath = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.fragment_mine)
        super.onCreate(savedInstanceState)
        setUserInfo()
        initAlbumTool()
    }

    override fun findView() {
        imgAvatar = findViewById(R.id.fg_mine_avatar) as ImageView
        ttvName = findViewById(R.id.fg_mine_name) as TextView
        ttvPhone = findViewById(R.id.fg_mine_phone) as TextView
        ttvAdress = findViewById(R.id.fg_mine_adress) as TextView
        ttvVipState = findViewById(R.id.fg_mine_vipstate) as ImageView
        ttvEditInfo = findViewById(R.id.fg_mine_edit) as TextView
        ttvVipBuy = findViewById(R.id.fg_mine_viplayout) as FrameLayout
        bttVipBuy = findViewById(R.id.fg_mine_vipbuy_btt) as Button
        ttvRestPass = findViewById(R.id.fg_mine_resetpass) as TextView
        ttvCollection = findViewById(R.id.fg_mine_collection) as TextView
        ttvMyPush = findViewById(R.id.fg_mine_mypush) as TextView
        ttvClearCache = findViewById(R.id.fg_mine_clearcache) as TextView
        ttvCheckUpdate = findViewById(R.id.fg_mine_checkupdate) as TextView
        ttvPrivacy = findViewById(R.id.fg_mine_privacy) as TextView
        ttvLogOff = findViewById(R.id.fg_mine_logoff) as TextView
        bttExitLogin = findViewById(R.id.fg_mine_exitlogin) as Button
    }


    override fun setListener() {
        ttvEditInfo.setOnClickListener {
            val intent = Intent(mContext, RegisterActivity::class.java)
            intent.putExtra("extral_page", 1)
            startActivity(intent)
        }
        ttvVipBuy.setOnClickListener {
            if (!userInfo!!.isVip()) {
                val intent = Intent(mContext, VipBuyActivity::class.java)
                intent.putExtra("extral_user", IdenEmum.TYPE_USER.identity)
                startActivity(intent)
            } else {
                showToastLong("敬的用户，您已经是VIP会员，会员有效期内无需重复购买！")
            }

        }

        bttVipBuy.setOnClickListener {
            if (!userInfo!!.isVip()) {
                val intent = Intent(mContext, VipBuyActivity::class.java)
                intent.putExtra("extral_user", IdenEmum.TYPE_USER.identity)
                startActivity(intent)
            } else {
                showToastLong("敬的用户，您已经是VIP会员，会员有效期内无需重复购买！")
            }

        }

        ttvRestPass.setOnClickListener {
            val intent = Intent(mContext, ResetPassActivity::class.java)
            intent.putExtra("extral_user", IdenEmum.TYPE_USER.identity)
            startActivity(intent)
        }

        ttvCollection.setOnClickListener {
            val intent = Intent(mContext, CollectionActivity::class.java)
            intent.putExtra("extral_user", IdenEmum.TYPE_USER.identity)
            startActivity(intent)
        }

        ttvMyPush.setOnClickListener {
            val intent = Intent(mContext, MyPushActivity::class.java)
            startActivity(intent)
        }

        ttvClearCache.setOnClickListener {
            showAlert()
        }

        ttvCheckUpdate.setOnClickListener {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                //Android 8.0以上
//                if (!mContext!!.packageManager.canRequestPackageInstalls()) {//是否有权限
//                    UpdateUtil.checkSetting(requireActivity(), intentActivityResultLauncher)
//                    showToast(mContext, "App版本更新需使用权限，请勾选相关权限！")
//                } else {//已经拥有权限
//                    UpdateUtil.checkUpdate(requireActivity(), true)
//                }
//            } else {
//                UpdateUtil.checkUpdate(requireActivity(), true)
//            }
            UpdateUtil.checkUpdate(requireActivity(), true)
        }

        ttvPrivacy.setOnClickListener {
            val intent = Intent(mContext, WebViewActivity::class.java)
            val url = "http://waste.biddingcloud.cn/privacy_agreement_in.html"
            intent.putExtra("extral_title", "用户隐私协议")
            intent.putExtra("extral_path", url)
            startActivity(intent)
        }

        ttvLogOff.setOnClickListener {
            showAlertLogOff()
        }

        bttExitLogin.setOnClickListener {
            showExitLoginAlert()
//            BaseUtil.sendMsg(mContext!!)
//            val paymentUtil = PaymentUtil()
//            paymentUtil.wxTest(mContext!!)
        }
    }

    val intentActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        if (result.resultCode == RESULT_OK) {
            UpdateUtil.checkUpdate(requireActivity(), true)
        }
    }

    /**
     *  @time 2025/6/7  11:08
     *  @desc 设置用户
     */
    private fun setUserInfo() {
        userInfo = MyApplication.instance.getUserInfo()
        if (!LCBaseUtil.isNull(userInfo?.nickName)) {
            ttvName.text = userInfo?.nickName
        } else {
            ttvName.text = userInfo?.account
        }
        ttvPhone.text = userInfo?.phone
        if (!LCBaseUtil.isNull(userInfo?.address)) {
            ttvAdress.text = userInfo?.address
        }
//        setTextValue(ttvName, userInfo?.account)
        setTextValue(ttvPhone, userInfo?.phone)
        setTextValue(ttvAdress, userInfo?.address)

        if ("VIP" == userInfo?.vip) {
            ttvVipState.visibility = View.VISIBLE
        } else {
            ttvVipState.visibility = View.GONE
        }
        loadAvatar(userInfo!!.avatar)
    }

    /**
     *  @time 2025/7/23  19:35
     *  @author Im_jingwei
     *  @desc 加载头像
     */
    private fun loadAvatar(avatarId: String) {
        val path = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_USER_AVATAR + avatarId
        Glide.with(requireActivity()).load(path).transform(CenterCrop(), RoundedCorners(20)).placeholder(R.mipmap.img_user_default)
            .error(R.mipmap.img_user_default).into(imgAvatar);
    }

    /**
     *  @time 2025/6/9  17:22
     *  @desc 获取用户信息
     */
    private fun requestUserInfo() {
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_USERINFO
        val token = LCSPUtil[mContext!!, AppConfig.SP_ACCESS_TOKEN]
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequestGet(url, token, object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                LCLogger.d(TAG, "获取用户信息失败！,${e.message}")
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONObject("data")
                    if (success) {
                        saveLoginInfo(mContext!!, data)
                        LCLogger.d(TAG, "获取用户信息成功！,登录信息：$jsonObject")
                    }
                } catch (e: Exception) {
                    LCLogger.d(TAG, "获取用户信息失败！,${e.message}")
                    e.printStackTrace()
                }
            }
        })
    }

    private fun saveLoginInfo(mContext: Context, json: JSONObject) {
        val userInfo = UserModel().apply { getModelInfo(json) }
        MyApplication.instance.setUserInfo(userInfo)
        LCSPUtil.save(mContext, AppConfig.SP_USER_ACCOUNT, json.getString("account"))
        LCSPUtil.save(mContext, AppConfig.SP_USER_ID, json.getString("userId"))
        LCSPUtil.save(mContext, AppConfig.SP_USER_AVATAR, json.getString("avatar"))
        LCSPUtil.save(mContext, AppConfig.SP_USER_PHONE, json.getString("phone"))
        activity?.runOnUiThread { setUserInfo() }
    }

    /**
     *  @time 2025/5/9  17:53
     *  @desc 清理缓存
     */
    private fun showAlert() {
        if (cacheDialog == null) {
            cacheDialog = SkAlertDialog(mContext)
            cacheDialog!!.setOnclickListener(mDeleteOnclickListener)
        }
        cacheDialog!!.setTitleAndContent("清除缓存提醒", "确定要清除程序运行产生的缓存吗？")
        cacheDialog!!.showExpend()
    }

    private val mDeleteOnclickListener = object : LCInterface.LcOnPnButtonClickLitener {
        override fun onNegetiveClick(vararg args: Any?) {
        }

        override fun onPositiveClick(vararg args: Any?) {
            LCSPUtil.save(mContext!!, AppConfig.SP_ACCESS_TOKEN, "")
            LCSPUtil.save(mContext!!, AppConfig.SP_USER_ACCOUNT, "")
            LCSPUtil.save(mContext!!, AppConfig.SP_USER_PASSWORD, "")
            LCSPUtil.save(mContext!!, AppConfig.SP_USER_ID, "")
            LCSPUtil.save(mContext!!, AppConfig.SP_USER_NAME, "")
            LCSPUtil.save(mContext!!, AppConfig.SP_USER_PHONE, "")
            LCSPUtil.save(mContext!!, AppConfig.SP_USER_AGREEMENT, "")
            showToastLong("缓存已清理！")
        }
    }


    /**
     *  @time 2025/5/9  17:53
     *  @desc 账户注销
     */
    private fun showAlertLogOff() {
        if (cacheDialog == null) {
            cacheDialog = SkAlertDialog(mContext)
            cacheDialog!!.setOnclickListener(mLogOffOnclickListener)
        }
        cacheDialog!!.setTitleAndContent("账户注销提醒", "    尊敬的用户，账户注销后不可恢复您所在本平台的一切权益将清除，确认要注销账户吗？")
        cacheDialog!!.setContentCenter(false)
        cacheDialog!!.showExpend()
    }


    private val mLogOffOnclickListener = object : LCInterface.LcOnPnButtonClickLitener {
        override fun onNegetiveClick(vararg args: Any?) {
        }

        override fun onPositiveClick(vararg args: Any?) {
            requestLogOff()
        }
    }

    /**
     *  @time 2024/5/7  11:29
     *  @desc 注销帐号
     *  @param url
     */
    private fun requestLogOff() {
        getMainActivity().showProgress()
        val httpUtil = OkHttpUtil()
        val token = LCSPUtil[mContext!!, AppConfig.SP_ACCESS_TOKEN]
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_CANCLEUSER
        httpUtil.httpRequest(url, token, "", object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                getMainActivity().cancleProgress()
                showToast(context, "账户注销失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    getMainActivity().cancleProgress()
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    if (success) {
                        showToastLong("您的注销申请已提交，我们将在24小时内为您注销账户！")
                        clearLoginInfo()
                    } else {
                        showToast(context, "账户注销失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    showToast(context, "账户注销失败，" + e.message)
                }
            }
        })
    }


    /**
     *  @time 2025/5/9  17:53
     *  @desc 退出登录
     */
    private fun showExitLoginAlert() {
        if (cacheDialog == null) {
            cacheDialog = SkAlertDialog(mContext)
            cacheDialog!!.setOnclickListener(mExitLoginOnclickListener)
        }
        cacheDialog!!.setTitleAndContent("退出登录提醒", "确定要退出当前账号吗？")
        cacheDialog!!.showExpend()
    }


    private val mExitLoginOnclickListener = object : LCInterface.LcOnPnButtonClickLitener {
        override fun onNegetiveClick(vararg args: Any?) {
        }

        override fun onPositiveClick(vararg args: Any?) {
            showToastLong("用户已退出，请重新登录！")
            clearLoginInfo()
        }
    }

    private fun setTextValue(textView: TextView, value: String?) {
        textView.text = if (isNull(value)) "" else value
    }


    /**
     *  @time 2024/11/14  10:29
     *  @author Im_jingwei
     *  @desc 选择照片
     */
    private fun initAlbumTool() {

        imgAvatar.setOnClickListener {
            if (PermissionUtil.instance.checkPermisssion(requireActivity(), Manifest.permission.CAMERA)) {
                albumSelectPopuWindow.showAtLocation(imgAvatar, Gravity.BOTTOM, 0, 0)
            } else {
                showToast(requireActivity(), "相机权限被拒绝，请授权或打开设置允许访问相机及多媒体权限！")
                PermissionUtil.instance.requesetPermission(requireActivity(), Manifest.permission.CAMERA)
            }
//            photoSelectUtil.album()
//            photoSelectUtil.camera()
        }

        photoSelectUtil = SKRPhotoSelectUtil.getInstance(this)
//            photoSelectUtil!!.setSelectSize(6)
        photoSelectUtil.setOnBackClick { string ->
            Log.d("LCLOG_AlbumSelect", string!!)
        }

        albumSelectPopuWindow = AlbumSelectPopuWindow()
        albumSelectPopuWindow.init(activity as AppCompatActivity)
        albumSelectPopuWindow.setPopuOnclickListener { view ->
            albumSelectPopuWindow.dismiss()
            when (view?.id) {
                R.id.popu_take_photo_compress -> {
                    photoSelectUtil.camera()
                }

                R.id.popu_take_album_press -> {
                    photoSelectUtil.album()
                }
            }
        }
    }

    /**
     *  @time 2025/1/21  17:42
     *  @author Im_jingwei
     *  @desc 裁剪图片选择回调
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != AppCompatActivity.RESULT_OK)
            return
        when (requestCode) {
            1 -> {
//                photoSelectUtil.dealAlbum(data)
                val path = photoSelectUtil.getFilePath(data)
                setAndUpdloadAvatar(path)
            }

            2 -> {
//                photoSelectUtil.dealCamera() //拍照可编辑不压缩
                val path = photoSelectUtil.filePath
                setAndUpdloadAvatar(path)
            }

            3 -> {
//                val currentPicturePath = photoSelectUtil.filePath
//                val pith = photoSelectUtil.tempPath
//                val bitmap = BitmapFactory.decodeFile(pith)
//                imgAvatar.setImageBitmap(bitmap)
//                uploadAttach(pith)
            }

            else -> {}
        }
    }

    private fun setAndUpdloadAvatar(path: String) {
//        val bitmap = BitmapFactory.decodeFile(path)
//        imgAvatar.setImageBitmap(bitmap)
        uploadAttach(path)
    }

    /**
     *  @time 2024/11/15  11:16
     *  @author Im_jingwei
     *  @desc 上传附件
     */
    private fun uploadAttach(filePath: String?) {
        if (LCBaseUtil.isNull(filePath)) {
            Log.d("LCLOG_CRASH", "无附件资料！---------------")
            return
        }
//        currentAvatarPath = filePath!!
        showProgress()

        val httpUtil = OkHttpUtil()
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_UPLOAD
        val token = LCSPUtil[mContext!!, AppConfig.SP_ACCESS_TOKEN]
        val params = HashMap<String, String>()
        httpUtil.httpRequestFile(url, token!!, "image", filePath!!, params, object : LCInterface.LcCallBackListener {
            override fun onSuccess(call: Call, response: String) {
//                val logfile = File(finalFilePath)
//                logfile.delete()
                val jsonObject = JSONObject(response)
                val msg = jsonObject.getString("msg")
                val avatarId = jsonObject.getString("location")
                if ("上传成功" == msg) {
                    activity!!.runOnUiThread { loadAvatar(avatarId) }
                }
//                isUploadingImage = false
                showToastLong("头像上传成功！")
                activity!!.runOnUiThread {
                    cancleProgress()
//                    setAvatar()
                }
                Log.d("LCLOG_CRASH", "附件文件已上传！---------------${response}")
            }

            override fun onFailure(call: Call, e: IOException) {
                showToastLong("头像上传失败,请重试！")
                Log.d("LCLOG_CRASH", "附件文件上传失败！---------------")
            }
        })
    }

    /**
     *  @time 2025/6/7  9:05
     *  @desc 清楚登录信息，重新登录
     */
    private fun clearLoginInfo() {
        LCSPUtil.save(mContext!!, AppConfig.SP_ACCESS_TOKEN, "")
        LCSPUtil.save(mContext!!, AppConfig.SP_USER_ACCOUNT, "")
        LCSPUtil.save(mContext!!, AppConfig.SP_USER_PASSWORD, "")
        val intent = Intent(mContext, LoginActivity::class.java)
        startActivity(intent)
        activity?.finish()
    }

    private fun getMainActivity(): MainActivity {
        return activity as MainActivity
    }

}